#!/usr/bin/env python
#
# Creates and imports a package installer representing a specific file in a
# custom "MCX" directory node.
#
# ARGS:
# 	<directory-node>
#		A directory in /var/db/dslocal/nodes/MCX/
#	<node-name>
#		The 'account' within the directory-node. This is expected to be
#		located in /var/db/dslocal/nodes/MCX/<directory-node>/<node-name>
#	<version-number>
#		An arbitrary version number that will be assigned to the resulting
#		package.
#
# Once this is complete, you should be able to locate the package in
# <munki-repo>/pkgs/MCXSettings/<directory-node>/edu.denison.mcx-<directory-node>_<node-name>.pkg
#
import sys
import os
import tempfile
import shutil
import subprocess

if os.getuid() != 0:
	sys.stderr.write("You must be root to run this script\n")
	sys.exit(1)

if len(sys.argv) < 4:
	sys.stderr.write('Usage: %s <directory-node> <node-name> <version-number>\n' % (sys.argv[0]))
	sys.exit(1)

dNode = sys.argv[1]
dAccount = sys.argv[2]
pkgVersion = sys.argv[3];
srcPlist = "/var/db/dslocal/nodes/MCX/%s/%s.plist" % (dNode, dAccount)

if not os.path.exists(srcPlist):
	sys.stderr.write("ERROR: Unable to locate '%s'\n" % srcPlist)
	sys.exit(1)

tmpPath = tempfile.mkdtemp()
payloadPath = "%s/payload" % tmpPath
postInstallScript = "%s/scripts/postinstall" % tmpPath

os.mkdir(payloadPath)
os.mkdir("%s/scripts" % tmpPath)
shutil.copy(srcPlist, payloadPath)

f = open(postInstallScript, "w")
f.write("""#!/bin/bash
rm -rf /var/db/dslocal/nodes/Desfult/sqlindex*
rm -rf /var/db/dslocal/nodes/MCX/sqlindex*
rm -rf /Library/Managed\ Preferences/*
rm -rf /Library/Managed\ Preferences/.GlobalPreferences.plist
killall opendirectoryd DirectoryService

echo "STARTING MCX REFRESH"
mcxrefresh -u 0
for user in `dscl localhost ls /Local/Default/Users | grep -ve "^_"`
do
	mcxrefresh -n "${user}"
done
echo "MCX REFRESH COMPLETE (it is safe to ignore messages about local_computer)"

exit 0""")
f.close()
os.chmod(postInstallScript, 0777)

pkgPath = "%s/mcx-%s_%s.pkg" % (os.getcwd(), dNode, dAccount)
print "THE PATH IS %s" % pkgPath
subprocess.call([
	"pkgbuild",
	"--root", payloadPath,
	"--version", pkgVersion,
	"--install-location", "/var/db/dslocal/nodes/MCX/%s/" % dNode,
	"--scripts", "%s/scripts" % tmpPath,
	"--identifier", "edu.denison.mcx-%s_%s" % (dNode, dAccount),
	pkgPath])
shutil.rmtree(tmpPath)

subprocess.call([
	"/usr/local/munki/munkiimport",
	"--catalog=dev",
	"--min-os-ver=10.7",
	"-d", "MCXSettings/%s" % (dNode),
	pkgPath])

os.remove(pkgPath)
